//添加树
var setting = {
			view: {
				dblClickExpand: false
			},
			data: {
				simpleData: {
					enable: true,
					idKey: "areaCode",
					pIdKey: "areaParentCode"
				},
				key:{
					name:"areaName"
				}
			},
			callback: {
				beforeClick: beforeClick,
				onClick: onClick
			}
		};

		

		function beforeClick(treeId, treeNode) {
			var check = (treeNode && !treeNode.isParent);
			if (!check) 
				new $.zui.Messager('只能选择地区!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			return check;
		}
		
		function onClick(e, treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("addtreeDemo"),
			nodes = zTree.getSelectedNodes(),
			v = ""; A = "";
			nodes.sort(function compare(a,b){return a.id-b.id;});
			for (var i=0, l=nodes.length; i<l; i++) {
				v += nodes[i].areaName + ",";
				A += nodes[i].areaCode ;
			}
			if (v.length > 0 ) v = v.substring(0, v.length-1);
			var cityObj = $("#citySel");
			cityObj.attr("value", v);
			var areaObj = $("#addArea_Code");
			areaObj.attr("value",A);
			console.log("地区编码="+A);
		}

		function showMenu() {
			var cityObj = $("#citySel");
			var cityOffset = $("#citySel").offset();
			$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");

			$("body").bind("mousedown", onBodyDown);
		}
		function hideMenu() {
			$("#menuContent").fadeOut("fast");
			$("body").unbind("mousedown", onBodyDown);
		}
		function onBodyDown(event) {
			if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
				hideMenu();
			}
		}
		$("#citySel").click(function(){
			 showMenu(); 
		});
$(document).ready(function() {
	var currentPage = 1;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");

	var devMaintainService = '/api/devMaintainInfo';

	var queryListFun = function() {
		//获取列表数据
		var queryListUrl = adminQueryUrl + devMaintainService + queryPageListMethod;

		var param = "";
		//搜索参数
		if ($("#queryDevInfCode").val() != '') {
			param += "queryDevInfCode=" + $("#queryDevInfCode").val();
		}
		if ($("#queryDevMaintainNameLike").val() != '') {
			param += "&queryDevMaintainNameLike=" + $("#queryDevMaintainNameLike").val();
		}
		if ($("#queryDevMaintainStatus").val() != '') {
			param += "&queryDevMaintainStatus=" + $("#queryDevMaintainStatus").val();
		}
		if (currentPage > 0) {
			param += "&currentPage=" + (currentPage - 1);
		}
		param += "&pageSize=" + pageSize;
		param += "&currentPage=" + (currentPage - 1);

		console.log('queryListUrl=' + queryListUrl);
		console.log('token=' + token + ",userId=" + userId);
		console.log('param=' + param);
		$.ajax({
			url: queryListUrl,
			type: 'post',
			beforeSend: function(xhr) {
				xhr.setRequestHeader("token", token);
				xhr.setRequestHeader("userId", userId);
			},
			header: {
				"token": token,
				"userId": userId
			},
			data: param,
			dataType: "JSON",
			success: function(result) {
				console.log(result.success);
				console.log(result.pageList);
				if (result.success == '1') {
					document.getElementById("queryDevMaintainStatus").options.length = 1;
					$.each(result.statusList, function(i, item) {
						if (item.key_value == result.searchMap.queryDevMaintainStatus) {
							$("#queryDevMaintainStatus").append("<option value='" + item.key_value + "' selected='selected'>" + item
								.key_name + "</option>");
						} else {
							$("#queryDevMaintainStatus").append("<option value='" + item.key_value + "'>" + item.key_name +
								"</option>");
						}
					});
					$('#listDataGrid').empty();
					$('#listDataGrid').data('zui.datagrid', null);
					$('#listPager').empty();
					$('#listPager').data('zui.pager', null);

					$('#listDataGrid').datagrid({
						checkable: true,
						checkByClickRow: true,
						selectable: true,
						dataSource: {
							cols: [{
									name: 'DevMaintain_ID',
									label: '主键',
									width: 0
								},
								{
									name: 'DevMaintain_Code',
									label: '故障编码',
									width: 150
								},
								{
									name: 'DevMaintainName',
									label: '故障名称',
									width: 134
								},
								{
									name: 'DevInf_Code',
									label: '设备编码',
									width: 109
								},
								{
									name: 'DevMaintainStatus_SLText',
									label: '故障状态',
									width: 109
								},
								{
									name: 'ContactName',
									label: '联系人名称',
									width: 109
								},
								{
									name: 'ContactTel',
									label: '联系人电话',
									width: 209
								},
								{
									name: 'FaultTime',
									label: '故障时间',
									width: 109
								},
								{
									name: 'Opr_Date',
									label: '操作时间',
									width: -1
								}
							],
							cache: false,
							array: result.pageList
						}

					});
					$('#listDataGrid').data('zui.datagrid').sortBy('DevMaintain_ID', 'asc');

					// 手动进行初始化
					$('#listPager').pager({
						page: currentPage,
						recPerPage: pageSize,
						elements: ['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text', 'size_menu',
							'goto'
						],
						pageSizeOptions: [5, 10, 20, 30, 50, 100],
						recTotal: result.pageTotal
					});
				} else {
					new $.zui.Messager(result.msg, {
						type: 'warning', // 定义颜色主题
						placement: 'center' // 定义显示位置
					}).show();
				}
			},
			error: function(result) {
				new $.zui.Messager('系统繁忙,请稍候再试!', {
					type: 'warning', // 定义颜色主题
					placement: 'center' // 定义显示位置
				}).show();
			}
		});
	};
	//调起查询数据
	queryListFun();

	//查询
	$("#searchBtn").click(function() {
		queryListFun();
	});
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		queryListFun();
	});
	//初始化添加
	$("#addBtn").click(function(){
		//获取所属厂商列表
		var url = adminQueryUrl + devMaintainService +initAddMethod ;
		var param = '';//请求到列表页面
		$("#addForm")[0].reset();
		console.log(url+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				if (data.success=='1'){
					document.getElementById("addMerDev_Code").options.length=1;
					$.each(data.merDevList, function(i, item){ 
						$("#addMerDev_Code").append("<option value='"+item.MerDev_Code+"'>"+item.MerDev_Code+"</option>");
					});
					$.fn.zTree.init($("#addtreeDemo"), setting, data.areaList);
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});

		
	});
	$('#AttachPath').uploader({
		autoUpload: true, // 当选择文件后立即自动进行上传操作
		url: adminQueryUrl + fileService + "?action=uploadDevImage1", // 文件上传提交地址
		limitFilesCount: 1,
		deleteActionOnDone:true,
	    deleteActionOnDone: function(file, doRemoveFile) {
	          doRemoveFile();
	      },
		responseHandler: function(responseObject, file) {
			if (responseObject != null && responseObject.response != null) {
				var resultJson = JSON.parse(responseObject.response);
				if (resultJson.success != null && resultJson.success != '' &&
					typeof(resultJson.success) != 'undefined' &&
					resultJson.fileName != '' &&
					typeof(resultJson.fileName) != 'undefined') {
					if (resultJson.success == '1') {
						$("#addAttachPath").val(adminQueryUrl + "/" + resultJson.fileName);
					}
				}
			}
		} //responseHandler
	});
	//添加保存
	$("#addSaveBtn").click(function(){
			$("#addForm").validate({
				rules:{
					addDevMaintainName:{
						"required":true
					},
					addMerDev_Code:{
						"required":true
					},
					addArea_Code:{
						"required":true
					},
					addContactName:{
						"required":true
					},
					addContactTel:{
						"required":true
					},
					addFaultTime:{
						"required":true
					},
					addRemark:{
						"required":true
					}
				},
				messages:{
					addDevMaintainName:{
						"required":"请输入设备故障名称！"
					},
					addMerDev_Code:{
						"required":"请选择设备号！"
					},
					addArea_Code:{
						"required":"请选择设备所属地区！",
					},
					addContactName:{
						"required":"请输入联系人名称！"
					},
					addContactTel:{
						"required":"请输入联系人电话！"
					},
					addFaultTime:{
						"required":"请输入故障时间！"
					},
					addRemark:{
						"required":"请输入故障描述！"
					}
				},
				submitHandler:function(form){
					console.log("xx:"+adminQueryUrl +  devMaintainService + addMethod);
					
					$.ajax({
						url:adminQueryUrl + devMaintainService + addMethod ,
						type:'post',
						dataType:'JSON',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						data:$(form).serialize(),
						success:function(data){
							console.log('添加data='+data);
							if (data.success == '1') {
			                	new $.zui.Messager('添加成功!', {
			    				    type: 'success',
			    				    placement:'center'
			    				}).show();
			                	queryListFun();
			                	$('#addModal').modal('hide', 'fit');
			                }
			                else{
			                	new $.zui.Messager(data.msg, {
			    				    type: 'warning',
			    				    placement:'center'
			    				}).show();
			                }
						},
						error:function(e){
							new $.zui.Messager('系统繁忙,请稍候再试!', {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
						}
					});
				}
			});	
	    });
	//初始化详情
	$("#detailBtn").click(function() {
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
				type: 'warning',
				placement: 'center'
			}).show();
		} else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
				type: 'warning',
				placement: 'center'
			}).show();
		} else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + devMaintainService + detailMethod;
			var param = 'DevMaintainId=' + selectedItems[0].DevMaintain_ID; //请求到列表页面
			console.log('详情param=' + param);
			$.ajax({
				url: url,
				type: 'post',
				dataType: 'JSON',
				beforeSend: function(xhr) { //设置请求头信息
					xhr.setRequestHeader("token", token);
					xhr.setRequestHeader("userId", userId);
				},
				header: {
					'token': token,
					'userId': userId
				},
				data: param,
				success: function(data) {
					console.log('详情data=' + data);
					if (data.success == '1') {

						$.each(data.statusList, function(i, item) {
							if (item.key_value == data.devMaintainMap.DevMaintainStatus_SL) {
								console.log(item.key_value + "==" + data.devMaintainMap.DevMaintainStatus_SL)
								$("#detailDevMaintainStatus").val(item.key_name);
							}
						});
						$("#detailDevMaintain_Code").val(data.devMaintainMap.DevMaintain_Code);
						$("#detailDevMaintainName").val(data.devMaintainMap.DevMaintainName);
						$("#detailMerDev_Code").val(data.devMaintainMap.MerDev_Code);
						$("#detailDevInf_Code").val(data.devMaintainMap.DevInf_Code);
						$("#detailOrg_Code").val(data.devMaintainMap.Org_Code);
						$("#detailAgeInf_Code").val(data.devMaintainMap.AgeInf_Code);
						$("#detailMerInf_Code").val(data.devMaintainMap.MerInf_Code);
						$("#detailArea_Code").val(data.devMaintainMap.Area_Code);
						$("#detailContactName").val(data.devMaintainMap.ContactName);
						$("#detailContactTel").val(data.devMaintainMap.ContactTel);
						$("#detailFaultTime").val(data.devMaintainMap.FaultTime);
						$("#detailSolveTime").val(data.devMaintainMap.SolveTime);
						$("#detailAttachPath").val(data.devMaintainMap.AttachPath);
						$("#detailRepairName").val(data.devMaintainMap.RepairName);
						$("#detailRepairBeginTime").val(data.devMaintainMap.RepairBeginTime);
						$("#detailRemark").val(data.devMaintainMap.Remark);
						$("#detailSolveRemark").val(data.devMaintainMap.SolveRemark);
						$("#detailSolveAttachPath").val(data.devMaintainMap.SolveAttachPath);
						$("#detailCrtUserId").val(data.devMaintainMap.CrtUserId);
						$("#detailCrtDate").val(data.devMaintainMap.Crt_Date);
						$("#detailUptUserId").val(data.devMaintainMap.UptUserId);
						$("#detailLastUptDate").val(data.devMaintainMap.Opr_Date);
					}
				},
				error: function(e) {
					new $.zui.Messager('系统繁忙,请稍候再试!', {
						type: 'warning',
						placement: 'center'
					}).show();
				}
			});
		}
	});
	//删除菜单
	$("#deleteSaveBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + devMaintainService + deleteMethod;
		var param = 'DevInfo_ID='+selectedItems[0].DevMaintain_ID;//请求到列表页面
		console.log('url='+url);
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
});
